import json
import multiprocessing
import os
import threading
import time, requests

from server.FlaskApp import StartServer
import setting
from server.module.textChat.textStore import TextStore


def StartMonitor():
    print("\n输入[?][help][--help][-help][-h][h]查看帮助")
    print(f"服务将运行于{setting.protocol}://{setting.host}:{setting.port}{setting.prefixURL}")
    while True:
        a = input()
        if a.lower() == 'u':
            print("打开上传文件夹" + setting.UploadPath)
            os.system(r'explorer "' + setting.UploadPath + '"')
        elif a.lower() == 'd':
            print("打开下载文件夹" + setting.DownloadPath)
            os.system(r'explorer "' + setting.DownloadPath + '"')
        elif a.lower() == 'f':
            print("打开程序文件夹")
            os.system(r'explorer ' + setting.RootPath)
        elif a.lower() == 'w':
            print("浏览器打开")
            cmd = 'start ' + setting.protocol + '://127.0.0.1:' + str(setting.port) + setting.prefixURL
            os.system(cmd)
        elif a.lower() == 'stop' or a.lower() == 'exit':
            pid = os.getpid()
            global tf
            tf.terminate()
            os.system(
                'taskkill /pid ' + str(pid) + ' -t -f'
            )
        elif a.startswith('/w '):
            requests.post(
                url=setting.protocol + '://127.0.0.1:' + str(setting.port) + '/chat/submitText',
                headers={'flagship': 'monitor'},
                data=json.dumps({
                    'content': a.lstrip('/w ')
                })
            )
        else:
            print('---------------------------------')
            print('[w] 浏览器打开\t\t[f] 打开程序文件夹')
            print('[u] 打开上传文件夹\t[d] 打开下载文件夹')
            print('[/w +文本] 发送文本到chat')
            print('[stop|exit] 关闭服务器')
            print('请选择功能：')
        #print('>', end='')


if __name__ == '__main__':
    tf = multiprocessing.Process(target=StartServer)
    tf.start()
    # tm = threading.Thread(target=StartMonitor)
    # tm.start()
    StartMonitor()
